package xj.graph2d.app;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

public class TemplatePanel 
  extends JPanel {

  public TemplatePanel() {
    setLayout(new BorderLayout());
    JPanel topPanel = new JPanel();
    choice = new JComboBox();
    choice.addItemListener(new TemplateListener());
    topPanel.add(choice);
    add(topPanel, BorderLayout.NORTH);
    centerPanel = new JPanel();
    centerPanel.setLayout(new CardLayout());
    add(centerPanel, BorderLayout.CENTER);
  }

  public void addTemplate(ToolPanel panel) {
    if (panel != null) {
      String display = panel.getDisplayName();
      choice.addItem(display);
      centerPanel.add(new JScrollPane(panel,
				      ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
				      ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER), 
		      display);
      panels.put(display, panel);
      currentToolPanel = panel;
    }
  }

  public void selectTemplate(String name) {
    //System.out.println("TemplatePanel.setTemplate() " + name);
    if (name != null) {
      choice.setSelectedItem(name);
      currentToolPanel = panels.get(name);      
    }
  }

  public JComboBox getChoiceComboBox() { 
    return choice;
  }

  public JPanel getPanel() { 
    return centerPanel;
  }

  public ToolPanel getCurrentToolPanel() { 
    return currentToolPanel;
  }

  protected JComboBox choice;

  protected JScrollPane scroll;

  protected JPanel centerPanel;

  protected ToolPanel currentToolPanel;
  protected Map<String, ToolPanel> panels = new HashMap<String, ToolPanel>();

  class TemplateListener implements ItemListener {

    public void itemStateChanged(ItemEvent event) {
      if (event.getStateChange() == ItemEvent.SELECTED) {
	Object item = event.getItem();
	if (item instanceof String) {
	  String sitem = (String) item;
	  CardLayout cl = (CardLayout) (centerPanel.getLayout());
	  cl.show(centerPanel, sitem);
	  currentToolPanel = panels.get(sitem);
	}
      }
    }

  }

}
